package com.cby.juc.线程.stop;

/**
 * ClassName: InterruptStop
 * Package: com.cby.juc.线程.stop
 * Description:
 *
 * @Author dhu-bion
 * @Create 2025/9/11 12:58
 * @Version 1.0
 */
public class InterruptStop {
    public static void main(String[] args){
        //实现runnable接口
        Runnable runnableThreadImpl = () ->{
            //获取当前子线程
            Thread currrentThread = Thread.currentThread();

//            //内部：检测中断状态
//            while(!currrentThread.isInterrupted()){
//                System.out.println("thread循环");
//            }

//            //interrupted()静态方法清除中断状态
//            while(!Thread.interrupted()){
//                System.out.println("thread循环2");
//            }

            //尝试中断阻塞态线程
            while(!currrentThread.isInterrupted()){
                System.out.println("thread循环");
                try {
                    Thread.sleep(20);
                } catch (InterruptedException e) {
                    //抛出异常并清除中断状态
                    //e.printStackTrace();

                    //解决方案：再次调用中断函数
                    currrentThread.interrupt();
                }

            }
        };

        //创建子线程
        Thread thread1 = new Thread(runnableThreadImpl);

        thread1.start();

        try {
            Thread.sleep(20);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }

        //外部：主线程中断子线程
        thread1.interrupt();

    }
}
